package com.pan.behavioral.observer;

import com.pan.behavioral.observer.traffic.lane.Lane;
import com.pan.behavioral.observer.traffic.lane.impl.EastWestLane;
import com.pan.behavioral.observer.traffic.lane.impl.NorthSouthLane;
import com.pan.behavioral.observer.traffic.TrafficLight;

import javax.swing.*;

/**
 * 观察者模式
 * Subject 发送状态
 *      这里是实现是subject包含了所有observer观察者类，通过publish方法告诉所有的的observer观察者
 * Observer 根据状态改变行为
 *      receive接收到状态改变 根据状态改变进行某种活动
 *
 * jdk有自带的观察者类 java.util.Observer 已经被弃用了
 *
 * java.awt 的事件 也是用了观察者模式
 * ActionListener 是观察者模式的 Observer
 *
 */
public class ObserverApplication {
    public static void main(String[] args) {
        TrafficLight trafficLight = new TrafficLight();
        String[] statuses = {"east-west: red; north-south: green;" ,
                "east-west: green; north-south: red;"};
        Lane ewLane = new EastWestLane();
        ewLane.setSubject(trafficLight);
        Lane nsLane = new NorthSouthLane();
        nsLane.setSubject(trafficLight);
        trafficLight.addObserver(ewLane);
        trafficLight.addObserver(nsLane);

        int index = 0;
        while (true){
            trafficLight.setStatus(statuses[index^=1]);
            trafficLight.publish();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
